import React, { useImperativeHandle, forwardRef, useState, useEffect } from 'react'
import { Input, Table, Button, Popover, Form, Space } from "antd";
import { ColumnsType } from "antd/lib/table";
import FormCondition from '@/components/FormCondition';
import _ from "lodash";
const f = (a, b) => [].concat(...a.map((d) => b.map((e) => [].concat(d, e))))
const cartesian = (a, b, ...c) => (b ? cartesian(f(a, b), ...c) : a)
const uuid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    // eslint-disable-next-line no-bitwise
    const r = (Math.random() * 16) | 0
    // eslint-disable-next-line no-bitwise
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
const SkuCreator = (props, ref) => {
  const { skus = [], onChange, propertyList, fatherForm, goodsSkuList = [] } = props
  const [totalProperties, setTotalProperties] = useState([]);
  const [isShowDetail, setIsShowDetail] = useState(false);
  const [columns, setColumns] = useState([]);
  const [rows, setRows] = useState(skus ? skus : []);
  const [openForm, setOpenForm] = useState(false)
  const [form] = Form.useForm();
  let falg = false;
  useImperativeHandle(ref, () => {
    return {
      getRowData: () => {
        return rows
      },
      getPropertyList: () => {
        return propertyList
      }
    }

  })
  useEffect(() => {
    let _isShowDetail = false;
    const _columns = [];
    const _rows = [];
    const properties = [];
    const pushList = [setOption({
      text: '重量',
      key: 'weight',
      fn: sku.onChangeWeight
    }), setOption({
      text: '划线价',
      key: 'oriPrice',
      hasPrefix: true,
      fn: sku.onChangeOldPrice
    }), setOption({
      text: <div> 售卖价 <span style={{ color: '#ff2929', paddingLeft: 4 }}>*</span></div>,
      key: 'price',
      hasPrefix: true,
      fn: sku.onChangePrice
    }), setOption({
      text: <div> 库存 <span style={{ color: '#ff2929', paddingLeft: 4 }}>*</span></div>,
      key: 'stock',
      fn: sku.onChangeStock
    }), setOption({
      text: '规格',
      key: 'skuCode',
      fn: sku.onChangeSku
    })]
    totalProperties.forEach((prop) => {
      if (prop.name && prop.values?.length) {
        const cartesianItem = [];
        _isShowDetail = true;
        _columns.push({
          title: prop.name,
          dataIndex: "properties",
          key: "properties",
        });

        prop.values.forEach((value) => {
          cartesianItem.push({
            name: prop.name,
            value,
          });
        });
        properties.push(cartesianItem);
      }
    });

    // // 使用笛卡尔乘积并根据属性计算所有可能的sku
    const cartesianProperties = cartesian(...properties);
    cartesianProperties?.forEach((e, i) => {
      _rows.push({
        key: i,
        skuId: uuid(),
        properties: Array.isArray(e) ? e : [e],
      });
    });
    ////////
    const colSpanArray = {};
    const rowCount = [];
    _rows.forEach((r, rindex) => {
      r.properties?.forEach((p, pindex) => {
        if (!colSpanArray[p.name]) {
          colSpanArray[p.name] = [];
        }
        if (rowCount[pindex] !== p.value) {
          colSpanArray[p.name].push(rindex - 1);
          rowCount[pindex] = p.value;
          if (rindex + 1 === _rows.length) {
            colSpanArray[p.name].push(rindex);
          }
        } else {
          if (rindex + 1 === _rows.length) {
            colSpanArray[p.name].push(rindex);
          }
        }
      });
    });
    _columns.forEach((c) => {
      c.render = (value, _, index) => {
        const item = value.find((v) => v.name === c.title);
        const obj = {
          children: item?.value,
          props: {},
        };
        obj.props.rowSpan = 0;
        colSpanArray[c.title]?.forEach((i, cindex) => {
          const prev = colSpanArray[c.title][cindex - 1];
          if (index === (prev === undefined ? 0 : prev + 1)) {
            obj.props.rowSpan = prev === undefined ? i + 1 : i - prev;
          }
        });
        return obj;
      };
    });
    pushList.forEach((item) => {
      _columns.push(item)
    })
    setIsShowDetail(_isShowDetail);
    setColumns(_columns);
    // 当totalProperties 发生改变时候就要重置行元素
    if (falg = true && goodsSkuList.length > 0) {
      setRows(_rows.map((item, index) => {
        falg = false
        let data = goodsSkuList[index] || {}
        return {
          ...data,
          ...item,
        }
      }));
    }
    else {
      setRows(_rows.map((item, index) => {
        let data = rows[index] || {}
        return {
          ...data,
          ...item,
        }
      }));
    }

  }, [totalProperties]);
  useEffect(() => {
    if (rows.length) {
      fatherForm.setFieldValue('price',
        rows.reduce((item, val, index) => {
          if (index === 0) {
            return val.price
          }
          else {
            return item
          }
        }, 0));
      fatherForm.setFieldValue('stock', rows.reduce((item, val, index) => {
        if (val.stock) {
          return Number(val.stock) + item
        }
        else {
          return item
        }
      }, 0));
    }
  }, [rows]);
  useEffect(() => {
    initSku()
  }, [skus])

  // 商品规格操作相关
  const sku = {
    onChangePrice(r, price) {
      setRows((prev) => {
        r.price = price;
        const ret = JSON.parse(JSON.stringify(prev));
        return ret;
      });
    },
    onChangeOldPrice(r, oriPrice) {
      setRows((prev) => {
        console.log(oriPrice, 12312332)
        r.oriPrice = oriPrice;
        const ret = JSON.parse(JSON.stringify(prev));
        return ret;
      });
    },
    onChangeStock(r, stock) {
      setRows((prev) => {
        r.stock = Number(stock);
        const ret = JSON.parse(JSON.stringify(prev));
        return ret;
      });
    },
    onChangeSku(r, skuCode) {
      setRows((prev) => {
        r.skuCode = skuCode;
        const ret = JSON.parse(JSON.stringify(prev));
        return ret;
      });
    },
    onChangeWeight(r, weight) {
      setRows((prev) => {
        r.weight = weight;
        const ret = JSON.parse(JSON.stringify(prev));
        return ret;
      });
    },
  };
  // 当商品规格发生改变时候改变数据

  const formItems = [
    {
      label: '重量(kg)',
      name: 'weight',
      type: 'number',
      rules: [{ required: false }],
    },
    {
      label: '售价',
      name: 'price',
      type: 'number',
      rules: [{ required: false }],
    },
    {
      label: '底价',
      type: 'number',
      name: 'oriPrice',
      rules: [{ required: false }],
    },
    {
      label: '库存',
      type: 'number',
      name: 'stock',
      rules: [{ required: false }],
    },
    {
      label: '规格',
      name: 'skuCode',
      rules: [{ required: false }],
    },
  ];

  const setOption = ({ text, key, fn, hasPrefix = false }) => {
    return {
      title: text,
      width: 120,
      dataIndex: key,
      key: key,
      render: (value, row, index) => {
        return (
          <Input
            prefix={hasPrefix ? "￥" : null}
            value={value}
            required
            onChange={(e) => fn(row, e.target.value)}
          />
        );
      },

    }
  }
  const SetShop = (props) => {
    return <div>
      <FormCondition form={form} formItems={formItems}></FormCondition>
      <div style={{ textAlign: 'right' }}>
        <Button onClick={() => { setOpenForm(false) }} style={{ marginRight: 12 }}>取消</Button>
        <Button type='primary' onClick={() => { BatchSettings() }}>确定</Button>
      </div>
    </div>
  }
  const BatchSettings = () => {
    form.validateFields().then(async (values) => {
      let batchList = Object.keys(values).filter(item => {
        return values[item]
      })
      let obj = {}
      batchList.forEach(item => {
        obj[item] = values[item]
      })
      setOpenForm(() => {
        setRows(rows.map(item => {
          return {
            ...item,
            ...obj
          }
        }))
        return false
      })
    });
  }
  const initSku = () => {
    const defaultProperties = []
    skus?.forEach((sku = {}) => {
      const { properties = [] } = sku
      properties.forEach((prop, i) => {
        if (prop.name && prop.value) {
          const currentProp = defaultProperties.find((p) => p.name === prop.name);
          if (currentProp) {
            !currentProp.values?.includes(prop.value) &&
              currentProp.values?.push(prop.value);
          } else {
            defaultProperties.push({
              name: prop.name,
              key: uuid(),
              values: [prop.value],
            });
          }
        }
      });

    });

    setTotalProperties(defaultProperties)
  }

  return (

    isShowDetail ? <div className='commodity_sku'>
      <div className='resource-section'>
        <div className='section-label'> 规格明细:</div>
        <div className='section-content'>

          <Table
            pagination={false}
            size="small"
            columns={columns}
            dataSource={rows}
            bordered
          // footer={() => 'Footer'}
          />


          <Popover placement="bottom" content={<SetShop></SetShop>} open={openForm}>
            <Button type='link' onClick={() => setOpenForm(true)}>批量设置</Button>
          </Popover>
        </div>
      </div>
    </div> : null


  );
}

export default forwardRef(SkuCreator);